package name.williamwall.buxoid;
/**
 * This software is made available under the Gnu General Public License v3
 * and has absolutely no waranty. You may change the software to suit your needs.
 * 
 * Author: William Wall, IV
 */
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TimePicker;
import android.widget.Toast;

public class EditSettings extends Activity {
	private BuxoidDb mDb;
	private EditText mUser, mPass;
	private Spinner mKeepData, mCurrencyCode;
	private Button mTime;
	private int mHour, mMin;
	private CheckBox mBalanceType, mScheduleUpdate, mNotifyBalance, mNotifyBudget;
	private PendingIntent mUpdateSender;
	
	private static SimpleDateFormat mReadFormat = new SimpleDateFormat("h m");
	private static SimpleDateFormat mWriteFormat = new SimpleDateFormat("h:mm a");
	
	@Override
	protected void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		mDb = new BuxoidDb(this);
		mDb.open();
		
		setTitle(R.string.title_settings);
		setContentView(R.layout.edit_settings);

		mUser = (EditText) findViewById(R.id.settings_user);
		mPass = (EditText) findViewById(R.id.settings_pass);
		mKeepData = (Spinner) findViewById(R.id.settings_num_years);
		mCurrencyCode = (Spinner) findViewById(R.id.settings_currency_code);
		mBalanceType = (CheckBox) findViewById(R.id.settings_balance_type);
		mScheduleUpdate = (CheckBox) findViewById(R.id.settings_schedule_update);
		mNotifyBalance = (CheckBox) findViewById(R.id.settings_notify_balance);
		mNotifyBudget = (CheckBox) findViewById(R.id.settings_notify_budget);
		mTime = (Button) findViewById(R.id.settings_update_time);
		Button password = (Button) findViewById(R.id.settings_buxoid_pass);
		Button reset = (Button) findViewById(R.id.settings_buxoid_reset);
		
		mTime.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				new TimePickerDialog(EditSettings.this, mTimeSetListener, mHour, mMin, false).show();
			}
		});
		
		password.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent i = new Intent(EditSettings.this, EditPassword.class);
				EditSettings.this.startActivity(i);
			}
		});
		
		reset.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				AlertDialog.Builder adb = new AlertDialog.Builder(EditSettings.this);
				adb.setCancelable(true);
				adb.setMessage("You are about to reset all of your data. Continue?");
				adb.setTitle("WARNING");
				adb.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface face, int num) {
						EditSettings.this.mDb.deleteAll();
					}
				});
				adb.setNegativeButton("No", null);
				adb.setIcon(android.R.drawable.ic_dialog_alert);
				adb.create().show();
			}
		});
		
		mScheduleUpdate.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
			public void onCheckedChanged(CompoundButton b, boolean isChecked) {
				// if sceduled updates are off, disable related options
				if (isChecked) {
					mTime.setEnabled(true);
					mTime.setText("Set Time");
					mNotifyBalance.setEnabled(true);
					mNotifyBudget.setEnabled(true);
				} else {
					mTime.setEnabled(false);
					mNotifyBalance.setChecked(false);
					mNotifyBalance.setEnabled(false);
					mNotifyBudget.setChecked(false);
					mNotifyBudget.setEnabled(false);
					
					AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
					
					// remove old alarm service, if any
					am.cancel(mUpdateSender);
				}
			}
		});
		
		mUpdateSender = PendingIntent.getService(this, 0, new Intent(this, UpdateService.class), 0);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		saveState();
	}

	@Override
	protected void onResume() {
		super.onResume();
		populateFields();
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		mDb.close();
	}

	private void populateFields() {
//		Log.d("Buxfer", "populating setting fields");
		mUser.setText(mDb.getSetting(BuxoidDb.SETTING_USER));
		mPass.setText(mDb.getSetting(BuxoidDb.SETTING_PASS));
		mKeepData.setSelection(Integer.parseInt(mDb.getSetting(BuxoidDb.SETTING_KEEP_DATA)));
		mCurrencyCode.setSelection(Integer.parseInt(mDb.getSetting(BuxoidDb.SETTING_CURRENCY_CODE)));
		mBalanceType.setChecked(mDb.getSetting(BuxoidDb.SETTING_BALANCE_TYPE).equals("1"));
		mScheduleUpdate.setChecked(mDb.getSetting(BuxoidDb.SETTING_SCHEDULE_UPDATE).equals("1"));
		
		// if sceduled updates are off, disable related options
		if (!mScheduleUpdate.isChecked()) {
			mTime.setEnabled(false);
			mNotifyBalance.setChecked(false);
			mNotifyBalance.setEnabled(false);
			mNotifyBudget.setChecked(false);
			mNotifyBudget.setEnabled(false);
		} else {
			mHour = Integer.parseInt(mDb.getSetting(BuxoidDb.SETTING_UPDATE_HOUR));
			mMin = Integer.parseInt(mDb.getSetting(BuxoidDb.SETTING_UPDATE_MINUTE));
			try {
				mTime.setText(mWriteFormat.format(mReadFormat.parse(mHour + " " + mMin)));
			} catch (ParseException e) {
//				Log.d("Buxfer", "could not create time string for button");
			}
			mNotifyBalance.setChecked(mDb.getSetting(BuxoidDb.SETTING_NOTIFY_BALANCE).equals("1"));
			mNotifyBudget.setChecked(mDb.getSetting(BuxoidDb.SETTING_NOTIFY_BUDGET).equals("1"));
		}
	}
	
	private void saveState() {
		mDb.putSetting(BuxoidDb.SETTING_USER, mUser.getText().toString().trim());
		mDb.putSetting(BuxoidDb.SETTING_PASS, mPass.getText().toString().trim());
		mDb.putSetting(BuxoidDb.SETTING_KEEP_DATA, mKeepData.getSelectedItemPosition() +"");
		mDb.putSetting(BuxoidDb.SETTING_CURRENCY_CODE, mCurrencyCode.getSelectedItemPosition() + "");
		mDb.putSetting(BuxoidDb.SETTING_BALANCE_TYPE, mBalanceType.isChecked() ? "1": "0");
		mDb.putSetting(BuxoidDb.SETTING_SCHEDULE_UPDATE, mScheduleUpdate.isChecked() ? "1": "0");
		if (mScheduleUpdate.isChecked()) {
			mDb.putSetting(BuxoidDb.SETTING_NOTIFY_BALANCE, mNotifyBalance.isChecked() ? "1": "0");
			mDb.putSetting(BuxoidDb.SETTING_NOTIFY_BUDGET, mNotifyBudget.isChecked() ? "1": "0");
			mDb.putSetting(BuxoidDb.SETTING_UPDATE_HOUR, mHour + "");
			mDb.putSetting(BuxoidDb.SETTING_UPDATE_MINUTE, mMin + "");
		}
		
		Toast.makeText(this, "Settings saved.", Toast.LENGTH_SHORT).show();
	}
	
	private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
		public void onTimeSet(TimePicker tp, int hour, int min) {
			mHour = hour;
			mMin = min;
			
			AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
			
			// calculate first run time
			Calendar c = Calendar.getInstance();
			c.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH), 0, 0);
			long time = hour * 60 * 60 * 1000 + min * 60 * 1000 + c.getTimeInMillis();
			time += time < System.currentTimeMillis() ? 24 * 60 * 60 * 1000: 0;
	
			// add alarm service
//			Log.d("Buxfer", "set alarm");
			am.setRepeating(AlarmManager.RTC_WAKEUP, time, 24 * 60 * 60 * 1000, mUpdateSender);

			c.setTimeInMillis(time);
			int tMonth, tDay, tHour, tMinute;
			tMonth = c.get(Calendar.MONTH);
			tDay = c.get(Calendar.DAY_OF_MONTH);
			tHour = c.get(Calendar.HOUR_OF_DAY);
			tMinute = c.get(Calendar.MINUTE);
			
			Toast.makeText(EditSettings.this, "First update set for " + tMonth + " / " + tDay + " at " + tHour + ":" + tMinute, Toast.LENGTH_SHORT);
			// set the time on the button so that the user will have an indication that the time is set
			try {
				mTime.setText(mWriteFormat.format(mReadFormat.parse(mHour + " " + mMin)));
			} catch (ParseException e) {
//				Log.d("Buxfer", "could not create time string for button");
			}
		}
	};
}
